using System;
using BCGC.DAL;
using System.Data;
using Jalal.Library.Web;
using Jalal.Library.Data;
using Jalal.Library.Utility;
using System.Data.SqlTypes;
using BCGC.BLL.Helper;
namespace BCGC.BLL.BusinessObject.UserAccount
{
    public class Admin : UserBase
    {
        public override bool IsAdmin
        {
            get { return true; }
        }

        public Admin()
        {
            this.id = 0;
            this.username = null;
            this.password = null;                                       
            this.lastLoginTime = SqlDateTime.MinValue.Value;
            this.invalidLoginCount = 0;
            this.email = null;
            this.createDateTime = SqlDateTime.MinValue.Value;
        }

        public Admin(DataRow dataRow)
        {
            if (dataRow != null)
            {
                if (dataRow.Table.Columns.Contains("Id"))
                    this.id = (int)dataRow["Id"];
                if (dataRow.Table.Columns.Contains("SiteUserName"))
                    this.username = (string)dataRow["SiteUserName"];

                this.password = null;                                       // Sensitive user data should not be loaded

                if (dataRow.Table.Columns.Contains("LastLoginTime"))
                    this.lastLoginTime = (DateTime)dataRow["LastLoginTime"];
                if (dataRow.Table.Columns.Contains("InvalidLoginCount"))
                    this.invalidLoginCount = (int)dataRow["InvalidLoginCount"];
                if (dataRow.Table.Columns.Contains("Email"))
                    this.email = (string)dataRow["Email"];
                if (dataRow.Table.Columns.Contains("CreateDateTime"))
                    this.createDateTime = (DateTime)dataRow["CreateDateTime"];
            }
            else
            {
                this.id = 0;
                this.username = null;
                this.password = null;
                this.lastLoginTime = SqlDateTime.MinValue.Value;
                this.invalidLoginCount = 0;
                this.email = null;
                this.createDateTime = SqlDateTime.MinValue.Value;
            }
        }

        public override void Login(string username, string password)
        {
            DataFactory.GetDataMiner().BeginTransaction(true);

            password = Security.Encrypt(password, Settings.SiteSettings.EncryptionKey, true);
            DataTable data = UserData.GetAdminUserByLoginInfo(username, password);

            DataFactory.GetDataMiner().CommitTransaction();

            if (data != null && data.Rows.Count > 0)
            {
                Admin admin = new Admin(data.Rows[0]);
                SessionManager.LoggedAdminUser = admin;
            }
        }

        public override void Logout()
        {
            SessionManager.LoggedAdminUser = null;
            SessionManager.ReturnUrl = CustomSiteMap.AdminHome;
        }
    }
}
